package org.study.hadoop.md.ch4;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.study.hadoop.md.util.MRDPUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 分层结构2：对嵌套好的文件，通过自连接操作创建问题、回复及评论层次
 */
public class QuestionAnswerBuildingDriver extends Configured implements Tool {

    public static class QuestionAnswerReducer extends Reducer<Text, Text, Text, NullWritable> {
        private ArrayList<String> answers = new ArrayList<String>();
        private String question = null;

        private String nestElements(String post, List<String> answers) {
            StringBuilder sb = new StringBuilder("P" + post);
            for (String answer : answers) {
                sb.append("\n\t" + "Q" + answer);
            }
            return sb.toString();
        }

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            question = null;
            answers.clear();
            for (Text text : values) {
                if (text.charAt(0) == 'Q') {
                    question = text.toString().substring(1, text.toString().length()).trim();
                } else {
                    answers.add(text.toString().substring(1, text.toString().length()).trim());
                }
            }
            if (question != null) {
                String postWithCommentChildren = nestElements(question, answers);
                context.write(new Text(postWithCommentChildren), NullWritable.get());
            }
        }
    }

    public static class PostCommentMapper extends Mapper<Object, Text, Text, Text> {
        private Text outKey = new Text();
        private Text outValue = new Text();

        @Override
        protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            String post = value.toString().charAt(0) == 'P' ? value.toString().substring(1, value.toString().length()).trim() : null;
            if (post != null) {
                int postType = Integer.parseInt(MRDPUtils.transformXmlToMap(post).get("PostTypeId"));
                if (post != null && postType == 1) {
                    outKey.set(MRDPUtils.transformXmlToMap(post).get("Id"));
                    outValue.set("Q" + value);
                } else {
                    outKey.set(MRDPUtils.transformXmlToMap(post).get("ParentId"));
                    outValue.set("A" + value);
                }
                context.write(outKey, outValue);
            }
        }
    }

    @Override
    public int run(String[] args) throws Exception {
        Path outPath = new Path("out");
        Path inPath = new Path("demo.txt");
        FileSystem fs = outPath.getFileSystem(getConf());
        if (fs.exists(outPath)) {
            fs.delete(outPath, true);
        }
        Job job = Job.getInstance(getConf(), "QuestionAnswerHierarchy");
        job.setJarByClass(QuestionAnswerBuildingDriver.class);
        job.setMapperClass(PostCommentMapper.class);
        job.setInputFormatClass(TextInputFormat.class);
        TextInputFormat.setInputPaths(job, inPath);
        job.setReducerClass(QuestionAnswerReducer.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        TextOutputFormat.setOutputPath(job, outPath);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static void main(String[] args) throws Exception {
        int res = ToolRunner.run(new Configuration(), new QuestionAnswerBuildingDriver(), args);
        System.exit(res);
    }
}
